package com.yyge.controller;

import cn.hutool.core.util.RandomUtil;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.yyge.context.AliyunContext;
import com.yyge.dto.R;
import com.yyge.dto.ResultCode;
import com.yyge.entity.Merchandiser;
import com.yyge.entity.SmsInfo;
import com.yyge.exception.ApplicationException;
import com.yyge.service.MerchandiserService;
import com.yyge.service.SmsInfoService;
import darabonba.core.client.ClientOverrideConfiguration;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 商家注册页面
 */
@RestController
@Api("商家招募")
public class RecruitController {
    @Autowired
    private MerchandiserService merchandiserService;
    @Autowired
    private SmsInfoService smsInfoService;

    @Autowired
    private AliyunContext aliyunContext;

    private static final int EXPIRES = 30;

    @PostMapping("/front/sms/register/validate")
    public R validate(@RequestBody SmsInfo smsInfo){
        QueryWrapper<SmsInfo> wrapper =new QueryWrapper<>(smsInfo);
        SmsInfo entity = smsInfoService.getOne(wrapper);
        System.out.println("======================");
        System.out.println(entity);
        System.out.println(entity.getSendTime()-System.currentTimeMillis());
        if(entity == null){
            /*验证码验证失败*/
            throw new ApplicationException(ResultCode.SYSTEM_REGISTER_CODE_ERROR);
        }
        if(entity.getSendTime()-System.currentTimeMillis()<0){
            /*验证码已过期*/
            throw new ApplicationException(ResultCode.SYSTEM_REGISTER_CODE_EXPIRE);
        }
        System.out.println(smsInfo);
        return null;
    }

    @GetMapping("/front/sms/register/{phpne}")
    @ApiOperation("发送验证码")
    public R sendSms(@PathVariable("phpne") String phone) throws ExecutionException, InterruptedException {
        Merchandiser UserName = new Merchandiser();
        UserName.setPhone(phone);
        QueryWrapper<Merchandiser> merchandiserWrapper = new QueryWrapper<>(UserName);
        Merchandiser merchandiser = merchandiserService.getOne(merchandiserWrapper);
        if (merchandiser != null) {
            /*判断当前有无该用户*/
            return R.error(ResultCode.ACCOUNT_NOT_EXISTS);
        }

        //检查是否已经存在验证码
        SmsInfo smsInfo1 = new SmsInfo();
        smsInfo1.setPhone(phone);

        QueryWrapper<SmsInfo> wrapper = new QueryWrapper<>(smsInfo1);
        List<SmsInfo> list = smsInfoService.list(wrapper);
        long now = System.currentTimeMillis();
        if(list.size() != 0){
            /*注册异常*/
           return R.error(ResultCode.SYSTEM_REGISTER_ERROR);
        }
//        SmsInfo one = list.get(0);
//
//        if (one != null) {
//            /*验证码错误*/
//            if (now < one.getSendTime().intValue() + EXPIRES * 1000) {
//                return R.error(ResultCode.SYSTEM_CODE_ERROR);
//            }
//        }

        //生产4位数验证码
        int code = RandomUtil.randomInt(1000, 9999);
        SmsInfo one = new SmsInfo(null, phone, code + "", now);
        doSend(code+"");
        smsInfoService.save(one);

        Map map = new HashMap();
        map.put("expired", EXPIRES);
        return R.ok(map);
    }


    public  void doSend(String code) throws ExecutionException, InterruptedException {
        AsyncClient client=null;
        try {
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    .accessKeyId(aliyunContext.getKeyid())
                    .accessKeySecret(aliyunContext.getKeysecret())
                    .build());

            client = AsyncClient.builder()
                    .region("cn-chongqing") // Region ID
                    .credentialsProvider(provider)
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                            .setEndpointOverride("dysmsapi.aliyuncs.com")
                    )
                    .build();

            // Parameter settings for API request
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName("阿里云短信测试")
                    .templateCode("SMS_154950909")
                    .phoneNumbers("13883817774")
                    .templateParam("{\"code\":\""+code+"\"}")
                    .build();


            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);

            SendSmsResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));
        } finally {
            client.close();
        }
    }
}
